package me.shurufa.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.adapter.ChatMessageAdapter;
import me.shurufa.model.MessageListResponse;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.widget.OnPageListener;
import me.shurufa.widget.ViewPageTracker;

/**
 * 会话消息列表Fragment 调用db>>调用废弃
 * 2016年1月26日 删除db逻辑 改用网络请求
 *
 * @FileName: me.shurufa.fragments.ChatMessageFragment.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-01-24 23:39
 */
public class ChatMessageFragment extends BaseListFragment implements OnPageListener {


    @Bind(R.id.list_view)
    ListView recyclerView;
    @Bind(R.id.ptr_refresh)
    PtrClassicFrameLayout ptrRefresh;

    ArrayList dataList;
    ChatMessageAdapter messageAdapter;
    ViewPageTracker tracker;
    private View footerView;
    public boolean isRequesting = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chat_message, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isRequesting = true;
//        自动刷新一次
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 400);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        //        初始化刷新
        setRefresh();
        dataList = new ArrayList();
        messageAdapter = new ChatMessageAdapter(getActivity(),dataList);
        tracker = new ViewPageTracker(this);
        recyclerView.setOnScrollListener(tracker);
        footerView = LayoutInflater.from(getActivity()).inflate(R.layout.load_more_view,recyclerView,false);
        footerView.setVisibility(View.GONE);
        recyclerView.addFooterView(footerView);
        recyclerView.setAdapter(messageAdapter);
    }


    private void setRefresh() {
        ptrRefresh.setResistance(2.0F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                boolean canbePullDown = PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, view, view1);
                return canbePullDown;
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }

    @Override
    protected void addDataToList(BaseResponse response, boolean isNew) {
        MessageListResponse resp = (MessageListResponse) response;
        if (isNew) {
            messageAdapter.clear();
        }
        messageAdapter.append(resp.data);
    }

    @Override
    protected void showEmptyView() {

    }

    @Override
    protected void hideEmptyView() {

    }

    @Override
    protected void setHasMore(boolean hasMore) {

    }


    @Override
    protected BaseResponse parseData(String data) {
        Gson gson = Global.getGson();
        return gson.fromJson(data, MessageListResponse.class);
    }

    @Override
    protected String cacheKey() {
        return "my_message";
    }


    @Override
    public void refresh() {
        super.refresh();
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh!=null&&ptrRefresh.isRefreshing()) {
                    ptrRefresh.refreshComplete();
                }
            }
        },2000);
        onRefresh();
    }

    public void onRefresh() {
        isRequesting = true;
        tracker.setmPage(1);
        loadData(1);
    }

    protected void loadData(final int page) {
        new RequestServerTask<MessageListResponse>(MessageListResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("page", String.valueOf(page));
                params.put("token",Global.currentUser.token);
                LogUtils.kLog().e(""+page);
                return HttpUtil.post(API.GET_MY_MESSAGE, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                endRefreshing();
            }

            @Override
            protected void onSuccess(MessageListResponse result) {
                if (result.data==null||result.data.length==0){
                    //没有更多数据 不能加载更多
                    isRequesting = true;
                    footerView.setVisibility(View.GONE);
                }else {
                    isRequesting = false;
                    if (page>1){
                        footerView.setVisibility(View.GONE);
                    }
                }
                bindData(result,page==1);

            }
        }.start();
    }

    public void endRefreshing() {
        if (ptrRefresh != null) {
            ptrRefresh.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (ptrRefresh!=null) {
                        ptrRefresh.refreshComplete();
                        if (messageAdapter.getCount() == 0) {
                            showEmptyView();
                        }
                    }
                }
            }, 500);
        }
    }


    //Viewpage tracker

    @Override
    public void onPageStart(int page) {
        isRequesting = true;
        if (page>1)
            footerView.setVisibility(View.VISIBLE);
        loadData(page);
    }

    @Override
    public boolean isRequesting() {
        return isRequesting;
    }

    @Override
    public void onScrollY(float listViewY) {

    }
}
